from rest_framework import serializers
from django_redis import get_redis_connection
from goods.models import SKU
from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex


class SKUSSerializers(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = '__all__'


class SKUSearchSerializer(HaystackSerializer):

    object = SKUSSerializers(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text','object')


class SKUHistorySerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    # 判断商品是否存在
    def validate(self, attrs):
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        return attrs

    def create(self, validated_data):
        # 获取当前用户
        user = self.context['request'].user
        sku_id = validated_data['sku_id']

        # 1,建立缓存对象
        conn = get_redis_connection('history')
        # 2,判断当前sku_id是否存在列表
        # 用连接对象生成管道对象pl
        pl = conn.pipeline()
        pl.lrem('history_%s'%user.id,0,sku_id)

        # 3,写入缓存
        pl.lpush('history_%s'%user.id,sku_id)
        # 4,控制数量
        pl.ltrim('history_%s'%user.id,0,4)

        pl.execute()


        return validated_data
